package com.api.aiyh_kafang.web;

import aiyh.utils.ApiResult;
import aiyh.utils.zwl.common.ToolUtil;
import com.api.aiyh_kafang.entity.UfInvoiceConfigDTO;
import com.api.aiyh_kafang.service.InvoiceService;
import com.api.aiyh_kafang.service.UploadByBase64Service;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import weaver.file.ImageFileManager;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

/**
 * @author EBU7-dev1-ayh
 * @create 2021/9/27 0027 14:13
 * upload invoice by base64 arr
 */


@Path("/kafang/upload")
public class UploadByBase64 {
	private final ToolUtil toolUtil = new ToolUtil();
	private final UploadByBase64Service uploadByBase64Service = new UploadByBase64Service();
	private final InvoiceService invoiceService = new InvoiceService();

	@Path("/uploadImage/byBase64")
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public String uploadImage(@Context HttpServletRequest request, @Context HttpServletResponse response,
	                          @RequestBody Map<String, String> base64Map) {
		int i = uploadByBase64Service.uploadImage(base64Map);
//		 上传完成过后，调用发票识别接口，将数据保存到建模表中
		User user = HrmUserVarify.getUser(request, response);
		JSONObject invoiceInfo = null;
		try {
			invoiceInfo = invoiceService.getInvoiceInfo(user, i);
			if (invoiceInfo == null || "1".equals(String.valueOf(invoiceInfo.get("status")))) {
				throw new RuntimeException(invoiceInfo == null ? "识别数据为空！" : invoiceInfo.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
			toolUtil.writeErrorLog("发票识别失败！" + e + invoiceInfo);
			return ApiResult.error("发票识别失败！");
		}
		try {
			invoiceService.saveInvoiceInfo(invoiceInfo, base64Map.get("requestId"));
		} catch (Exception e) {
			e.printStackTrace();
			toolUtil.writeErrorLog("发票保存失败！" + e);
			return ApiResult.error("发票保存失败！");
		}
		return ApiResult.success(i);
	}

	@Path("/getConfigInfo/{workflowId}")
	@GET
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public String getWorkflowId(@PathParam("workflowId") String workflowId) {
		UfInvoiceConfigDTO configInfo = invoiceService.getConfigInfo(workflowId);
		return ApiResult.success(configInfo);
	}


	@Path("/download/img/{fileId}")
	@GET
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public Response downloadFile(@PathParam("fileId") int fileId) throws IOException {
		try {
			InputStream inputStreamById = ImageFileManager.getInputStreamById(fileId);
			byte[] bytes = IOUtils.toByteArray(inputStreamById);
			StreamingOutput output = new StreamingOutput() {
				@Override
				public void write(OutputStream outputStream) throws IOException, WebApplicationException {
					outputStream.write(bytes);
//				byte[] buffer = new byte[1024*10];
//				int len = 0;
//				while ((len = inputStreamById.read(buffer)) != -1) {
//					outputStream.write(buffer, 0, len);
//				}
					outputStream.flush();
					outputStream.close();
				}
			};
			Response.ResponseBuilder header = Response.ok(output, MediaType.APPLICATION_OCTET_STREAM)
					.header("Content-Disposition",
							"attachment; filename=image_from_server.jpg");
			return header.build();
		} catch (Exception e) {
			return Response.ok(ApiResult.error("异常" + e), MediaType.APPLICATION_JSON).build();
		}
//		return ApiResult.success("成功");
	}
}
